package com.media.selector.media.model.loader

import android.annotation.SuppressLint
import android.content.ContentUris
import android.content.Context
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import androidx.loader.content.CursorLoader
import com.media.selector.media.model.entity.MimeType

/**
 * date        ：2020/5/12
 * author      ：蒙景博
 * description ：
 */
abstract class BaseCursorLoader(
    @NonNull context: Context,
    @Nullable projection: Array<String>?,
    @Nullable selection: String?,
    @Nullable selectionArgs: Array<String>?,
    @Nullable sortOrder: String?
) : CursorLoader(context, getContentUri(), projection, selection, selectionArgs, sortOrder) {

    companion object {
        const val COLUMN_BUCKET_ID = "bucket_id"
        const val COLUMN_BUCKET_DISPLAY_NAME = "bucket_display_name"

        const val AND = "AND"
        const val OR = "OR"

        const val BUCKET_ORDER_BY = "${MediaStore.MediaColumns.DATE_ADDED} DESC"

        fun getContentUri(): Uri = MediaStore.Files.getContentUri("external")

        // 是否是 Android 10 （Q） 之前的版本
        fun isAndroidQBeforeVersion(): Boolean = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
    }

    /**
     * 读取 Cursor，返回 Uri
     */
    protected fun getUri(cursor: Cursor): Uri {
        val id = cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID))
        val mimeType = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE))
        val contentUri = when {
            MimeType.isImage(mimeType) -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            MimeType.isVideo(mimeType) -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
            else -> getContentUri()
        }
        return ContentUris.withAppendedId(contentUri, id)
    }

    /**
     * 检查设备是否具有摄像头功能
     * @return 如果设备具有摄像头功能，则为true。否则为false。
     */
    @SuppressLint("UnsupportedChromeOsCameraSystemFeature")
    fun hasCameraFeature(): Boolean {
        return context.applicationContext.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)
    }
}